def read_text():
    content = ''
    with open('input/text_data.txt', 'r', encoding='utf-8') as f:
        content = f.read()
    return content

import base64
import csv
import json
import random
import requests
import os
import uuid

def gen_audio(text, output_file):
    appid = "8694880241"
    access_token= "phMLsOxGntkuYUGmbQ_x4IGPdjqU8uX7"
    cluster = "volcano_tts"

    voice_type = "BV002_streaming" # 通用男声
    # voice_type = "BV504_streaming"  # 美式英语 男
    # voice_type = "BV503_streaming"  # 美式英语 女
    host = "openspeech.bytedance.com"
    api_url = f"https://{host}/api/v1/tts"

    header = {"Authorization": f"Bearer;{access_token}"}

    request_json = {
        "app": {
            "appid": appid,
            "token": access_token,
            "cluster": cluster
        },
        "user": {
            "uid": "2103587455"
        },
        "audio": {
			"voice_type": voice_type,
            "encoding": "mp3",
            "speed_ratio": 1.0,
            "volume_ratio": 1.0,
            "pitch_ratio": 1.0,
        },
        "request": {
            "reqid": str(uuid.uuid4()),
            "text": text,
            "text_type": "plain",
            "operation": "query",
            "with_frontend": 1,
            "frontend_type": "unitTson"
        }
    }
    resp = requests.post(api_url, json.dumps(request_json), headers=header)
    print(f"resp body: \n{resp.json()}")
    if "data" in resp.json():
        data = resp.json()["data"]
        file_to_save = open(output_file, "wb")
        file_to_save.write(base64.b64decode(data))

if __name__ == '__main__':    
    # 清空并创建output目录
    output_dir = 'output'
    if os.path.exists(output_dir):
        print("\noutput文件夹已存在，包含以下内容：")
        for root, dirs, files in os.walk(output_dir):
            for name in files:
                print(f"文件: {os.path.join(root, name)}")
            for name in dirs:
                print(f"目录: {os.path.join(root, name)}")
        
        confirm = input("\n是否清空output文件夹？(y/n): ")
        if confirm.lower() == 'y':
            print("\n正在清空output文件夹...")
            for root, dirs, files in os.walk(output_dir, topdown=False):
                for name in files:
                    try:
                        os.remove(os.path.join(root, name))
                        print(f"已删除文件: {os.path.join(root, name)}")
                    except:
                        print(f"无法删除文件: {os.path.join(root, name)}")
                for name in dirs:
                    try:
                        os.rmdir(os.path.join(root, name))
                        print(f"已删除目录: {os.path.join(root, name)}")
                    except:
                        print(f"无法删除目录: {os.path.join(root, name)}")
        else:
            print("\n跳过清空output文件夹")
    
    try:
        os.makedirs(output_dir, exist_ok=True)
        print(f"\n已创建output目录: {output_dir}")
    except:
        print("\n无法创建output目录")

    # 生成音频文件
    txt = read_text()
    audio_output_dir = os.path.join(output_dir, 'audio.mp3')
    gen_audio(txt, audio_output_dir)
    print(f"\n音频文件已生成到目录：{audio_output_dir}")